<template>
  <el-dialog title="" v-model="dialogVisible" fullscreen>
    <waitInfoView ref="viewRef" />
    <el-divider content-position="left"> 设备维护单 </el-divider>
    <el-form size="large" ref="formRef" disabled :model="formData" :rules="formRules" label-width="120px"
      v-loading="formLoading">
      <el-row :gutter="24">

        <el-col :span="24">
          <el-form-item label="审核人" prop="reviewerId">
            <el-select size="large" clearable multiple filterable v-model="formData.reviewerId"
              placeholder="请选择审核人,支持模糊搜索">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="formData.startTime" type="datetime" value-format="x" placeholder="选择开始时间" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="formData.endTime" type="date" value-format="x" placeholder="结束时间" />
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="维护工时(小时)" prop="endTime">
            <el-input v-model="formData.hours" placeholder="" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="补充说明" prop="description">
            <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" v-model="formData.description" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="审核备注" prop="remark">
            <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 3 }" v-model="formData.remark" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="是否合格" prop="pass">
            <el-radio-group v-model="formData.pass">
              <el-radio v-for="item in getIntDictOptions(DICT_TYPE.KEEP_PASS)" :key="item.value" :value="item.value"
                :label="item.label" />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="附件" prop="files">
            <UploadFile v-model="formData.files" />
          </el-form-item>
        </el-col>


      </el-row>

    </el-form>

    <!-- 列表 -->
    <ContentWrap>

      <el-form-item>
        <div class="flex gap-2">
          <el-check-tag checked>{{ aletTitle }}</el-check-tag>
        </div>

      </el-form-item>

      <el-table ref="tableRef" @selection-change="handleRowCheckboxChange" border row-key="id" v-loading="loading"
        :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="维护项名称" align="center" prop="name" />
        <el-table-column label="维护方法" align="center" prop="keepMethod" />
        <el-table-column label="维护标准" align="center" prop="keepNorm" />
        <el-table-column label="描述" align="center" prop="description">
          <template #default="scope">
            <div class="rich-text-content" v-html="scope.row.description"></div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
    </ContentWrap>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { EquipmnetKeepWaitApi, EquipmnetKeepWait } from '@/api/business/equipmnetkeepwait'
import * as UserApi from '@/api/system/user'
import waitInfoView from './KeepWaitInfoView.vue'
import { EquipmentKeepSettingApi, EquipmentKeepSetting } from '@/api/business/equipmentkeepsetting'
import { KeepTaskApi, KeepTask } from '@/api/business/keeptask'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'

/** 待维护设备 表单 */
defineOptions({ name: 'EquipmnetKeepWaitForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const loading = ref(true) // 列表的加载中
const list = ref<EquipmentKeepSetting[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  keepType: undefined,
  name: undefined,
  status: undefined,
  createTime: []
})

// ✅ 定义 selectable 函数
const selectable = (row: any, index: number): boolean => {
  return false
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EquipmentKeepSettingApi.getEquipmentKeepSettingPageNewDamage(queryParams)
    list.value = data.list
    total.value = data.total

    nextTick(() => {
      list.value.forEach(row => {
        if (formData.value.itemSubComplete)
          if (formData.value.itemSubComplete.includes(row.id)) {
            tableRef.value?.toggleRowSelection(row, true)
          }
      })
    })

  } finally {
    loading.value = false
  }
}


const tableRef = ref()

const checkedIds = ref<number[]>([])

const handleRowCheckboxChange = (records: EquipmentKeepSetting[]) => {
  checkedIds.value = records.map((item) => item.id);
  console.log("当前选择的", checkedIds.value);

}

const formData = ref({
  id: undefined,
  waitId: undefined,
  equipmentId: undefined,
  startTime: undefined,
  endTime: undefined,
  reviewerId: undefined,
  reviewerName: undefined,
  itemId: undefined,
  itemSubId: undefined,
  itemSubComplete: [],
  description: undefined,
  reviewer_id: [],
  hours: undefined,
  pass: undefined,
  remark: undefined,
  files: []
})
const formRules = reactive({
  dutyUserId: [{ required: true, message: '责任人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const viewRef = ref()

const aletTitle = ref('')

const disableForm = ref(false)

//当前状态
const currentStatus = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await initData();
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据

  if (id) {
    formLoading.value = true
    try {
      const data = await EquipmnetKeepWaitApi.getEquipmnetKeepWaitDamage(id)
      //当前状态
      currentStatus.value = data.status
      //审核时禁用表单
      if (currentStatus.value == 23) {
        disableForm.value = true
      } else {
        disableForm.value = false
      }

      formData.value = data.taskRespVO
      const selectedIds = formData.value.itemSubComplete || []
      console.log("selectedIds", selectedIds);
      // 更新本地 checkedIds
      checkedIds.value = selectedIds
      queryParams.keepType = formData.value.itemId
      aletTitle.value = '维护类型:' + data.itemName + ''
      getList()

      nextTick(() => {
        list.value.forEach(row => {
          if (formData.value.itemSubComplete)
            if (formData.value.itemSubComplete.includes(row.id)) {
              tableRef.value?.toggleRowSelection(row, true)
            }
        })
      })

      console.log("viewRefviewRef", viewRef.value);
    } finally {
      viewRef.value.openDetailInfo(id, 1)
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

//用户列表
const userList = ref([])

const initData = async () => {
  userList.value = await UserApi.getSimpleUserList()
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求

  try {

    if (type == 23 || type == 25 || type == 20) {
      //如果是保存转审核 通过 驳回  还需要更新一下wait的状态
      if (type == 25 || type == 20) {
        if (formData.value.pass == undefined || formData.value.pass == null) {
          console.log("formData.value.pass", formData.value.pass, formData.value.remark);
          message.error("合格状态不能为空")
          return
        }
      }
      await updateWitStatus(formData.value.waitId, type);
    }


    if (type == 1 || type == 23 || type == 20 || type == 25) {
      //
      formData.value.itemSubComplete = checkedIds.value
      const data = formData.value as unknown as KeepTask
      await KeepTaskApi.updateKeepTaskDamage(data)
      message.success("提交成功")
    }


    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    formLoading.value = false
  } finally {

  }
}

const updateWitStatus = async (waitId, status) => {
  // 二次确认
  let title = "";
  if (status == 23) {
    title = "提交审核";
  }
  if (status == 20) {
    title = "驳回";
  }
  if (status == 25) {
    title = "通过";
  }

  await message.confirm("确认" + title + "?")
  // 确认接收
  const param = {
    id: waitId,//待维护
    status: status
  }
  await EquipmnetKeepWaitApi.updateKeepWaitAndTaskDamage(param)
  // 刷新列表
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    waitId: undefined,
    equipmentId: undefined,
    startTime: undefined,
    endTime: undefined,
    reviewerId: undefined,
    reviewerName: undefined,
    itemId: undefined,
    itemSubId: undefined,
    itemSubComplete: [],
    description: undefined,
    reviewer_id: [],
    hours: undefined,
    pass: undefined,
    remark: undefined,
    files: []
  }
  formRef.value?.resetFields()
}
</script>
